package com.anysoft.utils;

import java.text.SimpleDateFormat;

/**
 * Created by lty on 2018/5/10.
 */

public class DateTimeUtils {

    public static boolean isValidDateFormat(String s) {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            dateFormat.parse(s);
            return true;
        } catch (Exception e) {
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            return false;
        }
    }

    static int[] DAYS = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    /**
     * @param date yyyy-MM-dd
     * @return
     */
    public static boolean isValidDate(String date) {
        try {
            int year = Integer.parseInt(date.substring(0, 4));
            if (year <= 0)
                return false;
            int month = Integer.parseInt(date.substring(5, 7));
            if (month <= 0 || month > 12)
                return false;
            int day = Integer.parseInt(date.substring(8, 10));
            if (day <= 0 || day > DAYS[month])
                return false;
            if (month == 2 && day == 29 && !isGregorianLeapYear(year)) {
                return false;
            }
//            int hour = Integer.parseInt(date.substring(11, 13));
//            if (hour < 0 || hour > 23)
//                return false;
//            int minute = Integer.parseInt(date.substring(14, 16));
//            if (minute < 0 || minute > 59)
//                return false;
//            int second = Integer.parseInt(date.substring(17, 19));
//            if (second < 0 || second > 59)
//                return false;

        } catch (Exception e) {
            return false;
        }
        return true;
    }
    public static final boolean isGregorianLeapYear(int year) {
        return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
    }

    public static void main(String[] args) {
        System.out.println(isValidDate("2000-02-29"));
    }
}
